Page({
  data: {
    // 订单列表数据
    orders: [],
    
    // 倒计时定时器
    countdownTimer: null,
    
    // 订单状态类型
    orderStatus: {
      pending_payment: '等待支付订金',
      paid: '已预订成功',
      waiting_payment: '等待到店支付全款',
      completed: '您已全款支付',
      cancelled: '订单已取消'
    },
    
    // 模拟订单数据
    orderData: [
      {
        id: 'ORD001',
        carId: 1,
        carName: '特斯拉-Model 3 2022款后轮驱动版',
        carImage: 'https://images.unsplash.com/photo-1549317661-bd32c8ce0db2?w=400&h=300&fit=crop',
        year: '2022年',
        mileage: '1.27万公里',
        tags: ['男', '准新车', '0过户'],
        price: '26.18',
        downPayment: '5.68',
        status: 'pending_payment',
        statusText: '您的订单已生成，请在30分钟内支付订金',
        orderTime: '2024-01-15 14:30:25',
        paymentDeadline: Date.now() + 30 * 60 * 1000, // 30分钟后
        countdown: '',
        isHot: true
      },
      {
        id: 'ORD002',
        carId: 2,
        carName: '特斯拉-Model 3 2022款后轮驱动版',
        carImage: 'https://images.unsplash.com/photo-1549317661-bd32c8ce0db2?w=400&h=300&fit=crop',
        year: '2022年',
        mileage: '1.27万公里',
        tags: ['男', '准新车', '0过户'],
        price: '26.18',
        downPayment: '5.68',
        status: 'paid',
        statusText: '已预订成功，工作人员将尽快与您取得联系',
        orderTime: '2024-01-14 10:15:30',
        isHot: true
      },
      {
        id: 'ORD003',
        carId: 3,
        carName: '特斯拉-Model 3 2022款后轮驱动版',
        carImage: 'https://images.unsplash.com/photo-1549317661-bd32c8ce0db2?w=400&h=300&fit=crop',
        year: '2022年',
        mileage: '1.27万公里',
        tags: ['男', '准新车', '0过户'],
        price: '26.18',
        downPayment: '5.68',
        status: 'completed',
        statusText: '您已全款支付，工作人员将尽快与您沟通交付事宜',
        orderTime: '2024-01-13 16:45:12',
        isHot: true
      }
    ]
  },

  // 页面生命周期
  onLoad: function (options) {
    console.log('订单页面加载完成');
    this.loadOrderData();
  },

  onShow: function () {
    console.log('订单页面显示');
    // 每次显示页面时刷新订单数据
    this.loadOrderData();
    // 启动倒计时
    this.startCountdown();
  },

  onHide: function () {
    // 页面隐藏时清除倒计时
    this.clearCountdown();
  },

  onUnload: function () {
    // 页面卸载时清除倒计时
    this.clearCountdown();
  },

  // 加载订单数据
  loadOrderData: function() {
    // 模拟从服务器加载订单数据
    wx.showLoading({
      title: '加载中...'
    });

    setTimeout(() => {
      this.setData({
        orders: this.data.orderData
      });
      wx.hideLoading();
    }, 500);
  },

  // 返回上一页
  goBack: function() {
    // 检查页面栈，如果只有一页则跳转到主页
    const pages = getCurrentPages();
    if (pages.length <= 1) {
      wx.switchTab({
        url: '/pages/index/index'
      });
    } else {
      wx.navigateBack({
        delta: 1,
        success: () => {
          console.log('返回成功');
        },
        fail: () => {
          // 如果返回失败，跳转到主页
          wx.switchTab({
            url: '/pages/index/index'
          });
        }
      });
    }
  },

  // 取消订单
  cancelOrder: function(e) {
    const orderId = e.currentTarget.dataset.orderId;
    
    wx.showModal({
      title: '确认取消',
      content: '确定要取消这个订单吗？取消后订金将原路退回。',
      confirmText: '确认取消',
      cancelText: '再想想',
      confirmColor: '#ff4757',
      success: (res) => {
        if (res.confirm) {
          this.updateOrderStatus(orderId, 'cancelled');
          wx.showToast({
            title: '订单已取消',
            icon: 'success'
          });
        }
      }
    });
  },

  // 继续支付
  continuePay: function(e) {
    const orderId = e.currentTarget.dataset.orderId;
    const order = this.data.orders.find(o => o.id === orderId);
    
    wx.showModal({
      title: '确认支付',
      content: `确认支付订金 ￥${order.downPayment}万？`,
      confirmText: '确认支付',
      cancelText: '取消',
      success: (res) => {
        if (res.confirm) {
          // 模拟支付流程
          wx.showLoading({
            title: '支付中...'
          });
          
          setTimeout(() => {
            wx.hideLoading();
            this.updateOrderStatus(orderId, 'paid');
            wx.showToast({
              title: '支付成功！',
              icon: 'success'
            });
          }, 2000);
        }
      }
    });
  },

  // 联系客服
  contactService: function(e) {
    const orderId = e.currentTarget.dataset.orderId;
    
    wx.showActionSheet({
      itemList: ['拨打客服电话', '在线客服', '查看订单详情'],
      success: (res) => {
        switch(res.tapIndex) {
          case 0:
            wx.makePhoneCall({
              phoneNumber: '400-123-4567'
            });
            break;
          case 1:
            wx.showToast({
              title: '正在连接客服...',
              icon: 'loading'
            });
            break;
          case 2:
            this.viewOrderDetail(orderId);
            break;
        }
      }
    });
  },

  // 查看订单详情
  viewOrderDetail: function(orderId) {
    wx.navigateTo({
      url: `/pages/order-detail/order-detail?orderId=${orderId}`
    });
  },

  // 更新订单状态
  updateOrderStatus: function(orderId, newStatus) {
    const orders = this.data.orders.map(order => {
      if (order.id === orderId) {
        return {
          ...order,
          status: newStatus,
          statusText: this.getStatusText(newStatus)
        };
      }
      return order;
    });
    
    this.setData({
      orders: orders
    });
  },

  // 获取状态文本
  getStatusText: function(status) {
    const statusTexts = {
      pending_payment: '您的订单已生成，请在30分钟内支付订金',
      paid: '已预订成功，工作人员将尽快与您取得联系',
      waiting_payment: '等待到店支付全款',
      completed: '您已全款支付，工作人员将尽快与您沟通交付事宜',
      cancelled: '订单已取消'
    };
    return statusTexts[status] || '未知状态';
  },

  // 下拉刷新
  onPullDownRefresh: function() {
    this.loadOrderData();
    setTimeout(() => {
      wx.stopPullDownRefresh();
    }, 1000);
  },

  // 去看车
  goShopping: function() {
    wx.switchTab({
      url: '/pages/buy-car/buy-car'
    });
  },

  // 启动倒计时
  startCountdown: function() {
    this.clearCountdown();
    
    this.data.countdownTimer = setInterval(() => {
      const orders = this.data.orders.map(order => {
        if (order.status === 'pending_payment' && order.paymentDeadline) {
          const now = Date.now();
          const timeLeft = order.paymentDeadline - now;
          
          if (timeLeft > 0) {
            const minutes = Math.floor(timeLeft / (1000 * 60));
            const seconds = Math.floor((timeLeft % (1000 * 60)) / 1000);
            order.countdown = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
          } else {
            order.countdown = '00:00';
            order.status = 'cancelled';
            order.statusText = '支付超时，订单已取消';
          }
        }
        return order;
      });
      
      this.setData({
        orders: orders
      });
    }, 1000);
  },

  // 清除倒计时
  clearCountdown: function() {
    if (this.data.countdownTimer) {
      clearInterval(this.data.countdownTimer);
      this.setData({
        countdownTimer: null
      });
    }
  }
});
